﻿using Dapper;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Consumes("application/json")]

    // 基本资料：仓库控制器
    public class WarehouseController : ControllerBase
    {
        private readonly bs_WarehouseService bs_Warehouse;
        private readonly MyDbContext myDbContext;
        public WarehouseController(MyDbContext myDb, bs_WarehouseService bs_WarehouseService)
        {
            myDbContext = myDb;
            bs_Warehouse = bs_WarehouseService;
        }
        //查询
        [HttpGet]
        public async Task<IActionResult> Query()
        {
            var warehouse = await bs_Warehouse.Query();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询仓库状态值==1 “正常”
        [HttpGet]
        public async Task<IActionResult> IQuery()
        {
            var warehouse = await bs_Warehouse.Query();

            // 筛选出状态为1的数据
            //var filteredWarehouse = warehouse.Where(w => w.W_status == '1').ToList();
            var filteredWarehouse = warehouse.Where(w => w.W_status == '1' && w.W_lock).ToList();

            if (filteredWarehouse.Any())
            {
                return Ok(filteredWarehouse);
            }
            else
            {
                return NotFound("没有符合条件的仓库数据");
            }
        }
        //添加
        [HttpPost]
        public async Task<IActionResult> AddWarehouse(bs_Warehouse bs_warehouse)
        {

            // 查询当前最大编码
            int maxCodeNumber =int.Parse( await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateWarehouseCode(maxCodeNumber);

            bs_warehouse.W_code = newCode;
            // 设置默认的锁定状态，这里假设新仓库默认不锁定
            bs_warehouse.W_lock = false;
            // 添加新仓库
            await myDbContext.bs_Warehouse.AddAsync(bs_warehouse);
            await myDbContext.SaveChangesAsync();

            return Ok("添加成功！");
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.bs_Warehouse
                .Where(w => w.W_code.StartsWith("CK"))
                .Select(w => w.W_code.Substring(2))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "CK0001";
            }

            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了9999，则重置为0001
            if (newCodeNumber > 9999)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();
        }

        // 生成新的仓库编码
        private string GenerateWarehouseCode(int codeNumber)
        {
            // 将数字转换为四位字符串，并在前面补零
            string codeString = codeNumber.ToString("D4");

            // 返回完整的编码，包括前缀 "CK" 和数字部分
            return "CK" + codeString;
        }
        //修改
        [HttpPut]
        public async Task<IActionResult> updateWarehouse(bs_Warehouse bs_warehouse)
        {
            if (ModelState.IsValid)
            {
                int result = await bs_Warehouse.Update(bs_warehouse);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        //逻辑删除
        [HttpDelete("{W_Id}")]
        public async Task<IActionResult> DeleteWarehouse(int W_Id)
        {
            int result = await bs_Warehouse.Delete(W_Id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<bs_Warehouse>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "W_Id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_Warehouse"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_Warehouse>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_Warehouse> fenYe = new FenYe<bs_Warehouse>()
                {
                    warehouseData = result,
                    Rows = row,
                };

                if (fenYe.warehouseData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }
    }
}
